<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 工具栏 -->
      <PageTools :show-before="true">
        <!-- <template #before>左边</template>
        <template #after>右边</template> -->
        <template v-slot:before>
          <span>共 {{ total }} 条记录</span>
        </template>
        <template #after>
          <el-button size="small" type="warning" @click="$router.push('/employees/import?type=user')">导入</el-button>
          <el-button size="small" type="danger" @click="handleDownload">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column width="100px" label="序号" type="index" :index="indexFn" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" width="110px">
            <template #default="{row}">
              <!-- 下面写法肯定没问题，我期望能不能通过自定义指定封装的地方再次优化一下 -->
              <!-- <img v-imageerror="require('@/assets/common/head.jpg')" width="100" :src="row.staffPhoto || require('@/assets/common/head.jpg')"> -->
              <img v-imageerror="row.staffPhoto" width="80" :src="row.staffPhoto" @click="showQrCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" width="130px" />
          <el-table-column label="工号" prop="workNumber" />
          <!-- <el-table-column label="聘用形式" :formatter="formatEmployment" /> -->
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ formatEmployment(row) }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ row.formOfEmployment === 1 ? '正式' : '非正式' }}
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="部门" prop="departmentName" /> -->
          <el-table-column label="部门">
            <template #default="{row}">
              {{ row.departmentName | addLine }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="入职时间" prop="timeOfEntry" /> -->
          <el-table-column label="入职时间" width="170px">
            <template #default="{row}">
              {{ row.timeOfEntry | dateFormat }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态">
            <template #default="{row}">
              <!-- 1 表示启用，其他的是禁用 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <!-- //!#3 绑定点击事件 -->
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button :disabled="!checkPermission('EMPLOYEES_DEL')" type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 20, 30]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="changeSize"
            @current-change="changeCurrent"
          />
        </el-row>
      </el-card>
      <!-- 新增或编辑员工的弹框 -->
      <!-- 如果加了 sync 修复符 -->
      <!-- <add-employee :show-dialog="showDialog" @update:showDialog="showDialog=$event" /> -->
      <!-- 以后子组件只要进行 this.$emit('@update:showDialog', false) 就可以直接关闭弹框了 -->
      <add-employee :show-dialog.sync="showDialog" @addEmp="getEmployeeList" />
      <el-dialog title="图片二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- this.$emit('update:showRoleDialog', false) -->
      <!-- //!#3 传递 userId 到组件 -->
      <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
// import defaultImg from '@/assets/common/head.jpg'
import QrCode from 'qrcode'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      // defaultImg
      // defaultImg: require('@/assets/common/head.jpg'),
      query: {
        page: 1,
        size: 10
      },
      list: [],
      total: 0,
      loading: false,
      showDialog: false,
      showCodeDialog: false,
      // 控制角色弹框的显示隐藏
      showRoleDialog: false,
      // !#1 准备 userId
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async editRole(userId) {
      // !#2 记录当前点击行的 userId 到 data
      this.userId = userId
      // !#5 调用子组件获取角色列表的方法
      // !#6 报错了？？
      // 解决方式一：nextTick
      /* this.$nextTick(() => {
        this.$refs.assignRole.getUserDetailById()
      }) */
      // this.$nextTick(this.$refs.assignRole.getUserDetailById)
      /* this.$nextTick().then(() => {
        this.$refs.assignRole.getUserDetailById()
      }) */
      // 解决方式二：直接调用子组件的方法并传参
      await this.$refs.assignRole.getUserDetailById(userId)
      this.showRoleDialog = true
    },
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.query)
      this.list = rows
      this.total = total
      this.loading = false
    },
    indexFn(index) {
      // return index + 1
      return (this.query.page - 1) * this.query.size + (index + 1)
    },
    changeSize(size) {
      // 重置页码为 1
      this.query.page = 1
      this.query.size = size
      this.getEmployeeList()
    },
    changeCurrent(page) {
      this.query.page = page
      this.getEmployeeList()
    },
    formatEmployment(row) {
      // 对 row.formOfEmployment 进行判断
      const o = EmployeeEnum.hireType.find(item => item.id === +row.formOfEmployment)
      const value = o ? o.value : '未知'
      return value
    },
    async deleteEmployee(id) {
      try {
        await this.$confirm('确认删除吗')
        // 后端删了
        await delEmployee(id)
        if (this.list.length === 1 && this.query.page > 1) {
          this.query.page--
        }
        // 重新获取
        this.getEmployeeList()
        this.$message.success('删除成功')
      } catch {
        // ...
      }
    },
    handleDownload() {
      import('@/vendor/Export2Excel').then(async r => {
        // 获取所有数据
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.total
        })
        // 准备一个中引文对照表，key 会放到数组里面作为表头，value 会做 key 去 rows 中的每一对象中取值
        const headersRelations = {
          姓名: 'username',
          手机号: 'mobile',
          入职日期: 'timeOfEntry',
          聘用形式: 'formOfEmployment',
          转正日期: 'correctionTime',
          工号: 'workNumber',
          部门: 'departmentName'
        }
        // 准备 header 和 values
        // 单独的用 Object.keys 输出的顺序并不能保证是你写的这个对象的顺序
        const header = Object.keys(headersRelations)
        // console.log(header) // ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        // Object.keys 输出的 key 最终和 Object.values 输出的值一定是一一对象的
        const values = Object.values(headersRelations)
        // console.log(values) // ['username', 'mobile', 'timeOfEntry', 'formOfEmployment', 'correctionTime', 'workNumber', 'departmentName']

        // 组装二维数组
        const data = []
        // 循环后端返回的所有数据
        rows.forEach(item => {
          // 遍历 values
          const arr = []
          for (let i = 0; i < values.length; i++) {
            const key = values[i]
            // 此时此刻取的值其实是和 header 是一一对应的
            let v = item[key]
            // 处理时间相关的数据
            if (key === 'timeOfEntry' || key === 'correctionTime') {
              v = dayjs(v).format('YYYY-MM-DD')
            } else if (key === 'formOfEmployment') {
              // 处理聘用形式
              const o = EmployeeEnum.hireType.find(item => item.id === v)
              v = o ? o.value : '未知'
            }
            arr.push(v)
          }
          data.push(arr)
        })
        const multiHeader = [
          ['姓名', '主要信息', '', '', '', '', '部门']
        ]
        // 指定 merges 规则
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        r.export_json_to_excel({
          header,
          multiHeader,
          merges,
          data,
          filename: '学生信息表'
        })
      })
    },
    showQrCode(url) {
      /* if (url) {

      } else {
        this.$message.info('此图片线上地址不存在')
      } */
      if (!url) return this.$message.info('此图片线上地址不存在')
      // !数据更新到 DOM 变化的过程是异步的
      this.showCodeDialog = true
      // 如果想拿到渲染到 DOM 之后的结果，通过 this.$nextTick
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    }
  }
}
</script>
